__author__ = 'graced'

from PyQt4 import QtCore, QtGui
import urllib2
from xml.etree import ElementTree as ET
#This .py fle now parses XML and runs the GUI
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)
#Generates the GUI
class Ui_Form(object):
    def setupUi(self, Form, Query):
        tempForm = Ui_Form()
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(545, 545)
        self.horizontalLayoutWidget = QtGui.QWidget(Form)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(10, 0, 521, 51))
        self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
        self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setMargin(0)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.searchBar = QtGui.QTextEdit(self.horizontalLayoutWidget)
        self.searchBar.setEnabled(True)
        self.searchBar.setMaximumSize(QtCore.QSize(16777215, 30))
        self.searchBar.setObjectName(_fromUtf8("searchBar"))
        self.horizontalLayout.addWidget(self.searchBar)
        self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget)
        self.comboBox.setObjectName(_fromUtf8("comboBox"))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.horizontalLayout.addWidget(self.comboBox)
        self.searchButton = QtGui.QPushButton(self.horizontalLayoutWidget)
        self.searchButton.setText(_fromUtf8(""))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("searchButtonIcon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.searchButton.setIcon(icon)
        self.searchButton.setObjectName(_fromUtf8("searchButton"))
        self.horizontalLayout.addWidget(self.searchButton)
        self.line = QtGui.QFrame(Form)
        self.line.setGeometry(QtCore.QRect(0, 40, 541, 20))
        self.line.setFrameShape(QtGui.QFrame.HLine)
        self.line.setFrameShadow(QtGui.QFrame.Sunken)
        self.line.setObjectName(_fromUtf8("line"))
        self.toolBox = QtGui.QToolBox(Form)
        self.toolBox.setGeometry(QtCore.QRect(10, 70, 395, 800))
        self.toolBox.setObjectName(_fromUtf8("toolBox"))
        self.scrollArea = QtGui.QScrollArea(Form)
        self.scrollArea.setGeometry(QtCore.QRect(0, 45, 535, 450))
        self.scrollArea.setWidget(self.toolBox)
        tempForm.updateUI(self.toolBox, Query)

        self.retranslateUi(Form)
        self.toolBox.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(Form)
#Modified from the old version, toolboxes for cases are now generated dynamically
    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Medical Imaging Project", None))
        self.comboBox.setItemText(0, _translate("Form", "Case ID #", None))
        self.comboBox.setItemText(1, _translate("Form", "Medical Issue", None))
        self.comboBox.setItemText(2, _translate("Form", "Patient Name", None))
        self.comboBox.setItemText(3, _translate("Form", "Patient ID", None))
        #self.label.setText(_translate("Form", "This is a test for case 1.", None))
        #self.toolBox.setItemText(self.toolBox.indexOf(self.page), _translate("Form", "Case #1", None))
        #self.toolBox.setItemText(self.toolBox.indexOf(self.page_2), _translate("Form", "Case #2", None))
        #self.toolBox.setItemText(self.toolBox.indexOf(self.page_3), _translate("Form", "Case #3", None))
#Generates the section for the cases
    def createCases(self, toolBox, QueryResults):
        currentCase = 0
        while currentCase < QueryResults.__len__():
            controlName = "Case_" + str(currentCase)
            self.control = QtGui.QWidget()
            self.control.setGeometry(QtCore.QRect(0, 0, 391, 500))
            self.control.setObjectName(_fromUtf8(controlName))
            self.labelPatientName = QtGui.QLabel(self.control)
            self.labelPatientName.setGeometry(QtCore.QRect(0, 20, 161, 20))
            self.labelPatientName.setObjectName(_fromUtf8("labelPatientName"))
            self.labelPatientName.setText(_fromUtf8("Patient Name: " + QueryResults[currentCase].getData('PatientName')))
            self.labelDescription = QtGui.QLabel(self.control)
            self.labelDescription.setGeometry(QtCore.QRect(0, 40, 500, 20))
            self.labelDescription.setObjectName(_fromUtf8("labelDescription"))
            self.labelDescription.setText(_fromUtf8("Description: " + QueryResults[currentCase].getData('DerivationDescription')))
            toolBox.addItem(self.control, _fromUtf8(""))
            currentCaseText = "Case #" + str(currentCase + 1)
            toolBox.setItemText(toolBox.indexOf(self.control), _fromUtf8(currentCaseText))
            currentCase += 1
#Dynamically modifies the GUI without reloading
    def updateUI(self, toolBox, QueryResults):
        self.createCases(toolBox, QueryResults)

#Class for getting/showing case (text) data
class Case:
    def __init__(self):
        self.key = []
        self.value = []
        self.data = {}

    def addData(self, key, value):
        self.data[key] = value

    def getAllData(self):
        return self.data

    def getData(self, key):
        return self.data[key]

class RiakQuery:
    def __init__(self):
        pass
#Runs the riak query
    def executeQuery(self, field, value):
        cases = []
        #The field is entered by the user, the value is gotten from the resulting XML file.
        # This value will also be the thing that relates this report to an image
        URL = "http://localhost:8098/search/query/xml1?q=dicom.image."+field+":"+value+"&wt=python"
        connection = urllib2.urlopen(URL)
        response = eval(connection.read())

        for document in response['response']['docs']:
            currentCase = Case()
            XML = "http://localhost:8098/types/xml1/buckets/xml1/keys/"+document['_yz_rk']
            tree = ET.ElementTree(file=urllib2.urlopen(XML))
            root = tree.getroot()
            metaData = {}
            imageData = {}

            for node in root.getchildren()[0]:
                metaData[node.tag] = node.text
            for node in root.getchildren()[1]:
                imageData[node.tag] = node.text
                for item in node.findall("item"):
                    itemCounter = 1
                    for subItem in item:
                        imageData[subItem.tag+"_"+str(itemCounter)] = subItem.text
                        itemCounter += 1

            for item in metaData:
                currentCase.addData(item, metaData[item])

            for item in imageData:
                currentCase.addData(item, imageData[item])

            cases.append(currentCase)

        return cases
#Runs the GUI
if __name__ == "__main__":
    import sys
    tempQuery = RiakQuery()
    app = QtGui.QApplication(sys.argv)
    Form = QtGui.QWidget()
    ui = Ui_Form()
    #ui.setupUi(Form, tempQuery.executeQuery("SliceLocation", "13.88194752").__len__())
    ui.setupUi(Form, tempQuery.executeQuery("SliceLocation", "*"))
    Form.show()
    sys.exit(app.exec_())
